<template>
  <div class="login-page">
    <el-card>
      <template #header>黑马面经运营后台</template>
      <el-form autocomplete="off" :model="form" :rules="rules" ref="form">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="输入用户名" v-model="form.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="输入用户密码" v-model="form.password"></el-input>
        </el-form-item>

        <el-form-item class="tc">
          <el-button type="primary" @click="handleLogin">登 录</el-button>
          <el-button @click="resetForm">重 置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginForm } from '@/api/user'
export default {
  name: 'login-page',
  data () {
    return {
      form: {
        username: 'admin6',
        password: 'admin'
      },
      rules: {
        // 非空判断
        username: [
          { required: true, message: '需要输入账号', trigger: ['blur', 'change'] },
          { min: 3, max: 10, message: '需要3-10', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '需要输入密码', trigger: ['blur', 'change'] },
          { min: 3, max: 10, message: '需要3-10', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    async handleLogin () {
      // 处理登录需要验证表单
      await this.$refs.form.validate()
      try { // 发送请求获取token
        const res = await loginForm(this.form)
        console.log(res.data.token)
        // 传送到state=>mutations
        this.$store.commit('user/setUserToken', res.data.token)
        this.$message.success('登录成功，过两秒进行跳转')
        // 过两秒跳转
        setTimeout(() => {
          this.$router.push('/')
        }, 2000)
      } catch (error) {
        console.log(error)
      }
    },
    resetForm () {
      // 重置表单
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  display: flex;
  align-items: center;
  justify-content: space-around;
  .el-card {
    width: 420px;
    ::v-deep .el-card__header{
      height: 80px;
      background: rgba(114,124,245,1);
      text-align: center;
      line-height: 40px;
      color: #fff;
      font-size: 18px;
    }
  }
  .el-form {
    padding: 0 20px;
  }
  .tc {
    text-align: center;
  }
}
</style>
